<template>
    <div class="level-from">
        <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="240px" class="ruleForm" :disabled="!!detail">
            <el-form-item label="" label-width="0" v-if="formData.state  == 0 && !formData.examineState && !detail">
                <el-button type="success" @click="saveData('ruleForm')">保存</el-button>
            </el-form-item>

            <el-form-item label="目标标准名称" prop="name">
                <el-input v-model="formData.name" ></el-input>
            </el-form-item>
            <el-form-item label="所属诊改阶段" prop="year">
                <el-select v-model="formData.year"  placeholder="请选择所属诊改阶段">
                    <el-option v-for="year in yearArr" :key="year" :label="year" :value="year"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="责任部门" prop="dutyPart" required>
                <el-select v-model="formData.dutyPart" filterable placeholder="请选择责任部门"  @change="changeDept">
                    <el-option
                            :label="item.orgName"
                            :value="item.id"
                            v-for="item in organizeArr"
                            :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="dutyUser">
                <el-select v-model="formData.dutyUser" filterable placeholder="请选择负责人" disabled>
                    <el-option :label="item.realName" :value="item.id" v-for="(item,index) in deptUserArr"
                               :key="index"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="管理员" prop="adminId">
                <el-select v-model="formData.adminId" filterable placeholder="请选择管理员" disabled>
                    <el-option :label="item.realName" :value="item.id" v-for="(item,index) in deptUserArr"
                               :key="index"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="适用范围" prop="rectificationRangeId">
                <el-cascader
                        @change="changeRange"
                        v-model="formData.rectificationRangeId"
                        :options="rectificationRange"
                        :show-all-levels="false"
                        :props="{label: 'name',value: 'id'}"
                        >
                </el-cascader>
            </el-form-item>
            <!-- 后台不存，仅做展示 -->
            <template v-if="rangeChildList.length > 1">
                <el-form-item v-for="(item,index) in rangeChildList" :key="index" :label="`诊改对象-${item.name}`" class="response">
                    <el-input type="textarea" disabled v-model="item.rectificationObjectStr"></el-input>
                </el-form-item>
            </template>
            <el-form-item v-else label="诊改对象" class="response" prop="rectificationObjectStr">
                <el-input type="textarea" disabled v-model="formData.rectificationObjectStr"></el-input>
            </el-form-item>

            <el-form-item label="本部门参与人" prop="joinUsers">
                <el-select v-model="formData.joinUsers" multiple filterable placeholder="请选择本部门参与人" @change="$forceUpdate()">
                    <template v-for="(item,index) in deptUserArr">
                        <el-option
                                :label="item.realName"
                                :value="item.id"
                                :key="index"></el-option>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item label="参与部门" prop="joinOrgs" class="response" :style="{ 'display': joinOrgHidden ? 'none' : '' }">
                <el-select v-model="formData.joinOrgs" multiple filterable placeholder="请选择参与部门" @change="$forceUpdate()">
                    <el-option
                            :label="item.orgName"
                            :value="item.id"
                            v-for="item in organizeArr"
                            :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="共享人" prop="shareUsers">
                <el-col style="width: 48%;" v-if="!detail">
                    <el-select v-model="tempOrg" filterable placeholder="请先选择共享人部门"  @change="changeDept(tempOrg, true)">
                        <el-option
                                :label="item.orgName"
                                :value="item.id"
                                v-for="item in organizeArr"
                                :key="item.id"></el-option>
                    </el-select>
                </el-col>
                <el-col :style="!detail?'margin-left: 4%; width: 48%':' width: 100%'">
                    <el-select v-model="formData.shareUsers" :disabled="formData.examineState>0" multiple filterable placeholder="请选择共享人" @change="$forceUpdate()">
                        <el-option
                                :label="item.realName"
                                :value="item.id"
                                v-for="(item,index) in shareUserDataArr"
                                :key="index">
                            {{ item.realName }}
                            <!-- <p style="float: right; color: #8492a6; font-size: 13px;padding-right: 15px">所属部门：{{ item.orgName || '无' }}</p> -->
                        </el-option>
                    </el-select>
                </el-col>
            </el-form-item>

            <el-form-item label="备注" prop="desc" class="response">
                <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8}" v-model="formData.desc"></el-input>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import { getAllOrganize, getUserByDept, getAdminAndChargeByOrgId } from '../../../../api/systemManage';
    import { getStrByRangeId } from '../../../../api/system';
    import { deepClone, getStorage } from '../../../../config/utils';

    export default {
        name: 'levelFrom',
        props: {
            addParams: {
                type: Object
            },
            // 详情
            formInfo: {
                type: Object
            },
            disabled: {
                type: Boolean,
                default: false
            },
            // 是不是模板
            isModel: {
                type: Boolean,
                default: false
            },
            // 确定是哪个层面的
            levelType: {
                type: String
            },
            detail: {
                type: String
            },
            joinOrgHidden: Boolean
        },
        computed: {
            // 适用范围
            rangeList () {
                const temp = getStorage('rangeList');
                temp.forEach(item => {
                    item.id = 0;
                    item.subList = [...item.rectificationRangeDTOList];
                });
                return temp
            }
        },
        data () {
            return {
                formData: {
                    parentId: '',
                    sourceId: '',
                    rectificationRangeId: [],
                    rectificationObjectStr: '',
                    year: '',
                    dutyPart: '',
                    dutyUser: '',
                    joinUsers: [],
                    shareUsers: [],
                    desc: '',
                    joinOrgs: []
                },
                yearArr: this.$config.yearArr(),
                // 责任部门
                organizeArr: [],
                rules: {
                    name: [
                        { required: true, message: '请输入目标标准名称', trigger: 'blur' }
                    ],
                    year: [
                        { required: true, message: '请选择年度', trigger: 'change' }
                    ],
                    dutyPart: [
                        { required: true, message: '请选择责任部门' }
                    ],
                    rectificationRangeId: [
                        { required: true, message: '请选择适用范围' }
                    ],
                    rectificationObjectStr: [
                        { required: true, message: '诊改对象不能为空' }
                    ]
                },
                // 共享人
                shareUserDataArr: [],
                tempOrg: null,
                // 本部门参与人
                deptUserArr: [],
                // 适用范围（角度=也就是页面上tab值）
                rectificationRange: [],
                // 所选适用范围下的三级数据
                rangeChildList: [],
                // 根据适用范围回显的诊改对象
                rectificationObject: []
            }
        },
        created () {
            this.getOrganize();
            // this.getAllUser();
            const temp = getStorage('rangeList');
            temp.forEach(item => {
                if (item.code === this.levelType) {
                    this.rectificationRange = item.rectificationRangeDTOList
                }
            });
        },
        methods: {
            saveData (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        const params = { ...this.formData }
                        const len = params.rectificationRangeId.length - 1;
                        params.rectificationRangeId = params.rectificationRangeId[len];
                        this.$emit('saveData', params)
                    } else {
                        return false;
                    }
                })
            },
            // 获取责任部门下拉数据
            getOrganize () {
                getAllOrganize().then(res => {
                    this.organizeArr = res || []
                }).catch()
            },
            // 根据选中的适用范围回显诊改对象
            changeRange (val) {
                const temp = this.rectificationRange.filter(item => {
                    if (item.id === val[0]) {
                        return item.subList
                    }
                })
                if (temp.length && temp[0].subList) {
                    this.rangeChildList = temp[0].subList
                    this.rangeChildList.forEach((item, index) => {
                        this.getRangeList(item.id, index)
                    })
                } else {
                    this.rangeChildList = []
                    getStrByRangeId({ rangeId: val[0] }).then(res => {
                        this.$set(this.formData, 'rectificationObjectStr', res)
                    })
                }
            },
            getRangeList (rangeId, index) {
                getStrByRangeId({ rangeId: rangeId }).then(res => {
                    this.$set(this.rangeChildList[index], 'rectificationObjectStr', res)
                })
            },
            // 适用范围根据最后一级Id,反查前2级的id
            getRangeParent (id) {
                let arr = [];// 定义一个空数组
                const options = this.rangeList;// 拿到的所有数据集合（树状）
                this.$nextTick(() => {
                    if (!options && options.legth <= 0) return;
                    fun(options); // 调用封装好的回显函数
                    let out = false;// 定义一个标识（是否找到对应的id）
                    function fun (childrenArr) { // 封装的回显函数
                        let bg = 0; // 定义一个标杆（标识循环到当前数组的第几条）
                        for (const item of childrenArr) {
                            if (item.id === id) { // 判断所在数组（层级），是否有与之匹配的id
                                arr.push(item.id);// 存在则返回其id
                                out = true;// 存在就将标识设置为true
                                return;// 递归出口（出口1）
                            } else if (item.subList && item.subList.length > 0) {
                                // 判断id不匹配的层级是否具有下级目录（children）
                                arr.push(item.id);
                                fun(item.subList);// 存在下级目录就将下一级目录回调
                            }
                            bg++;
                            if (out) return// 如果找到对应的id 就执行返回 （出口2）
                            if (bg === childrenArr.length && arr && arr.length > 0) {
                                arr = [];// 如果在最后一个数组对象都没有找到对应ID 那么就清空数组
                            }
                        }
                    }
                    // arr;//最后将其赋值给默认选中数组
                    this.formData.rectificationRangeId = arr
                });
            },
            // 获取所有用户
            // getAllUser() {
            //     getAllUser().then(res => {
            //         this.userDataArr = res || []
            //     }).catch(() => {})
            // },
            // 根据部门查询用户、管理员和负责人
            changeDept (val, isShareDept) {
                this.formData.joinUsers = []
                getUserByDept(val).then(res => {
                    if (isShareDept) {
                        this.shareUserDataArr = new Set([...this.shareUserDataArr, ...res]);
                    } else {
                        this.deptUserArr = res || [];
                    }
                }).catch(() => {})
                if (!isShareDept) {
                    getAdminAndChargeByOrgId(val).then(res => {
                        if (res) {
                            this.$set(this.formData, 'dutyUser', res.chargePerson)
                            this.$set(this.formData, 'adminId', res.adminPerson)
                        }
                    }).catch(() => {})
                }
            }
        },
        watch: {
            formInfo: {
                handler (val) {
                    this.formData = JSON.parse(JSON.stringify(val));
                    this.formData.rectificationRangeId = val.rectificationRangeId ? [val.rectificationRangeId] : [];
                    if (val.rectificationRangeId) {
                        this.changeRange(this.formData.rectificationRangeId);
                        // this.getRangeParent(val.rectificationRangeId)
                    }
                    if (val.dutyPart) {
                        getUserByDept(val.dutyPart).then(res => {
                            this.deptUserArr = res || []
                        }).catch(() => {})
                    }
                    if (val.joinMemberDTOList) {
                        const temp1 = []
                        val.joinMemberDTOList.forEach(item => {
                            temp1.push(item.relationId)
                        })
                        // this.formData.joinUsers = [...temp1]
                        this.formData.joinUsers = deepClone(temp1)
                    }
                    if (val.shareMemberDTOList) {
                        const temp2 = []
                        val.shareMemberDTOList.forEach(item => {
                            temp2.push(item.relationId)
                            this.shareUserDataArr.push({
                              id: item.relationId,
                              realName: item.relationName
                            })
                        })
                        this.formData.shareUsers = [...temp2]
                    }
                    if (val.joinOrgDTOList) {
                        const temp3 = []
                        val.joinOrgDTOList.forEach(item => {
                            temp3.push(item.relationId)
                        })
                        this.formData.joinOrgs = [...temp3]
                    }
                },
                deep: true
            }
        }
    }
</script>

<style lang="scss" scoped>
    .level-from{
        width: 60%;
    }
</style>
